
package com.greenantmall.version;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.greenantmall.R;
import com.greenantmall.AntHomeApplication;
import com.greenantmall.bean.VersionInfo;
import com.greenantmall.utils.Const;
import com.greenantmall.utils.iLog;

import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 下载管理
 * 
 */
public class DownloadManager {

    private Context mContext;
    private VersionInfo versionEntry = null;

    final static int CHECK_FAIL = 0;
    final static int CHECK_SUCCESS = 1;
    final static int CHECK_NOUPGRADE = 2;
    final static int CHECK_NETFAIL = 3;
    private final static String TAG = "DownloadManager";

    private AlertDialog noticeDialog; // 提示弹出框
    private ProgressDialog progressDialog;

    private boolean isAccord; // 是否主动检查软件升级
    private SimpleDateFormat days = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat seconds = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    private boolean needDialog;
/**
 * 
 * @param mContext
 * @param isAccord 主动检查升级
 * @param needDialog 是否显示对话框
 */
    public DownloadManager(Context mContext, boolean isAccord,
            boolean needDialog) {
        this.mContext = mContext;
        this.isAccord = isAccord;
        this.needDialog = needDialog;
    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case CHECK_SUCCESS: {
                    if (needDialog) {
                        showNoticeDialog();
                    } else {
                        //TODO检查更新的广播
//                        Intent intent = new Intent(Macro.broadcast_version_update);
//                        mContext.sendBroadcast(intent);
                    }
                    break;
                }
                case CHECK_NOUPGRADE: { // 不需要更新
                    if (isAccord && needDialog)
                        Toast.makeText(mContext, "当前已是最新版本", Toast.LENGTH_SHORT)
                                .show();
                    break;
                }
                case CHECK_NETFAIL: {
                    if (isAccord && needDialog)
                        Toast.makeText(mContext, "网络连接失败", Toast.LENGTH_SHORT)
                                .show();
                    break;
                }
                case CHECK_FAIL: {
                    if (isAccord && needDialog)
                        Toast.makeText(mContext, "当前已是最新版本", Toast.LENGTH_SHORT)
                                .show();
                    break;
                }
            }
        };
    };

    /* 检查下载更新 [apk下载入口] */
    public void checkDownload() {
        // if(isAccord) progressDialog = ProgressDialog.show(mContext, "",
        // "请稍后，正在检查更新...");
        new Thread() {
            @Override
            public void run() {
                if (!IntentUtil.isConnect(mContext)) { // 检查网络连接是否正常
                    handler.sendEmptyMessage(CHECK_NETFAIL);
                } else if (checkTodayUpdate() || isAccord) {// 判断今天是否已自动检查过更新
                                                            // ；如果手动检查更新，直接进入
                                                            // alreayCheckTodayUpdate();
                                                            // // 设置今天已经检查过更新



                    versionEntry = HttpRequestUtil.getSourceResult();
                    try {
                        if (versionEntry != null) {
                            if (checkUpdateFlag(versionEntry.getVersionCode())) { // 检查版本号
                                AntHomeApplication.newVersonName=versionEntry.getVersionName();
                                handler.sendEmptyMessage(CHECK_SUCCESS);
                                iLog.d("AntHomeApplication.newVersonName:"+AntHomeApplication.newVersonName);
                            } else {
                                AntHomeApplication.newVersonName="";
                                handler.sendEmptyMessage(CHECK_NOUPGRADE);
                                iLog.d("AntHomeApplication.newVersonName:"+AntHomeApplication.newVersonName);
                            }
                        } else {
                            AntHomeApplication.newVersonName="";
                            handler.sendEmptyMessage(CHECK_FAIL);
                            iLog.d("AntHomeApplication.newVersonName:"+AntHomeApplication.newVersonName);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        AntHomeApplication.newVersonName="";
                        handler.sendEmptyMessage(CHECK_FAIL);
                        iLog.d("AntHomeApplication.newVersonName:"+AntHomeApplication.newVersonName);
                    }
                }

            }
        }.start();
    }

    /* 弹出软件更新提示对话框 */
    private void showNoticeDialog() {
        noticeDialog = new AlertDialog.Builder(mContext).create();
        int width = noticeDialog.getWindow().getWindowManager()
                .getDefaultDisplay().getWidth();
        noticeDialog.show();
        Window window = noticeDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

        noticeDialog.getWindow().setContentView(R.layout.pop_update_version);
        TextView versionInfo = (TextView) noticeDialog.getWindow()
                .findViewById(R.id.versionInfo);
        TextView updateInfo = (TextView) noticeDialog.getWindow().findViewById(
                R.id.updateInfo);
        updateInfo.setText(versionEntry.getDesc());
        versionInfo.setText("更新提示(V" + versionEntry.getVersionName()
                + ")");
        TextView updateLater = (TextView) noticeDialog.getWindow()
                .findViewById(R.id.update_later);

        updateLater.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // 在这里添加48小时后更新的提醒
                noticeDialog.dismiss();
                laterUpdate();
            }
        });

        TextView updateNow = (TextView) noticeDialog.getWindow().findViewById(
                R.id.update_now);
        updateNow.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                String apkPath = Const.apkSavepath
                        + versionEntry.getVersionCode(); // apkinfo.getApkName();
                // String apkPath = versionEntry.getDownloadUrl();
                DownloadCallback downCallback = new DownloadInstall(mContext,
                        apkPath, versionEntry.getVersionName(),
                        versionEntry.getVersionCode());
                // 传入文件大小
                DownloadAsyncTask request = new DownloadAsyncTask(downCallback,
                        mContext, versionEntry.getFileSize());
                request.execute(versionEntry.getUrl(), apkPath);
                noticeDialog.dismiss();
            }
        });
    }

    /**
     * 根据日期检查是否需要进行软件升级
     * 
     * @throws Exception
     */
    private boolean checkTodayUpdate() {
        //不加时间限制，每次启动都检查更新
        if(true)
            return true;
        SharedPreferences sharedPreference = mContext.getSharedPreferences(
                UpdateShared.SETTING_UPDATE_APK_INFO, 0);
        String checkDate = sharedPreference.getString(UpdateShared.CHECK_DATE,
                "");
        String updateDate = sharedPreference.getString(
                UpdateShared.UPDATE_DATE, "");
        if ("".equals(checkDate) && "".equals(updateDate)) { // 刚安装的新版本，设置详细信息
            String dateStr = seconds.format(new Date());
            sharedPreference.edit().putString(UpdateShared.CHECK_DATE, dateStr)
                    .commit();
            // .putInt(UpdateShared.APK_VERCODE, verCode).commit();
            return true;
        }
        alreayCheckTodayUpdate(); // 设置今天已经检查过更新
        try {
            // 判断defaultMinUpdateDay天内不检查升级
            if (checkDate.equalsIgnoreCase(days.format(new Date()))) {
                return false;
            } else if ((new Date().getTime() - seconds.parse(updateDate)
                    .getTime()) / (1000 * 3600) < Const.defaultMinUpdateHours) {// 判断今天是否检查过升级
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
        return true;
    }

    /**
     * 设置今天已经检查过升级
     * 
     * @return
     */
    private void alreayCheckTodayUpdate() {
        String date = days.format(new Date());
        SharedPreferences sharedPreference = mContext.getSharedPreferences(
                UpdateShared.SETTING_UPDATE_APK_INFO, 0);
        sharedPreference.edit().putString(UpdateShared.CHECK_DATE, date)
                .commit();
    }

    private void laterUpdate() {
        SharedPreferences sharedPreference = mContext.getSharedPreferences(
                UpdateShared.SETTING_UPDATE_APK_INFO, 0);
        sharedPreference
                .edit()
                .putString(UpdateShared.UPDATE_DATE, seconds.format(new Date()))
                .commit();
    }

    /**
     * 检查版本是否需要更新
     * 
     * @return
     */
    private boolean checkApkVerName() {
       
            return true;
        
    }

    /**
     * 检查版本是否需要更新
     * 
     * @return
     */
    private boolean checkUpdateFlag(int versionCode)
    {
        if (getCurrentVersionCode() < versionCode)
            return true;
        return false;
    }

    static interface UpdateShared {
        String SETTING_UPDATE_APK_INFO = "cbt_upgrade_setting";
        String UPDATE_DATE = "updatedate";
        String APK_VERSION = "apkversion";
        String APK_VERCODE = "apkvercode";
        String CHECK_DATE = "checkdate";
    }

    private int getCurrentVersionCode()
    {
        try
        {
            PackageManager manager = mContext.getPackageManager();
            PackageInfo info = manager.getPackageInfo(
                mContext.getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e)
        {
            e.printStackTrace();
            return 0;
        }
    }
}
